package com.xbts.system.service.impl;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbts.common.constant.UserConstants;
import com.xbts.common.core.domain.model.LoginUser;
import com.xbts.common.exception.ServiceException;
import com.xbts.common.utils.StringUtils;
import com.xbts.system.domain.CnWorkOrder;
import com.xbts.system.domain.vo.CnWorkOrderDetailVO;
import com.xbts.system.enums.WorkOrderStatusEnum;
import com.xbts.system.service.ICnWorkOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xbts.system.mapper.CnWorkOrderDetailMapper;
import com.xbts.system.domain.CnWorkOrderDetail;
import com.xbts.system.service.ICnWorkOrderDetailService;
import com.xbts.common.utils.DateUtils;
import com.xbts.common.utils.SecurityUtils;

/**
 * 工单详细Service业务层处理
 * 
 * @author xbts
 * @date 2023-08-28
 */
@Service
public class CnWorkOrderDetailServiceImpl  extends ServiceImpl<CnWorkOrderDetailMapper, CnWorkOrderDetail> implements ICnWorkOrderDetailService {

    @Autowired
    private ICnWorkOrderService cnWorkOrderService;

    /**
     * 查询工单详细列表
     *
     * @param cnWorkOrderDetail 工单详细
     * @return 工单详细
     */
    @Override
    @Transactional
    public List<CnWorkOrderDetailVO> selectCnWorkOrderDetailList(CnWorkOrderDetail cnWorkOrderDetail) {
        if (StringUtils.isEmpty(cnWorkOrderDetail.getOrderNum())) {
            throw new ServiceException("工单号不能为空");
        }
        LambdaQueryWrapper<CnWorkOrderDetailVO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CnWorkOrderDetail::getOrderNum, cnWorkOrderDetail.getOrderNum());
        queryWrapper.orderByDesc(CnWorkOrderDetail::getCreateTime);


        // 更新
        LambdaUpdateWrapper<CnWorkOrderDetail> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CnWorkOrderDetail::getOrderNum, cnWorkOrderDetail.getOrderNum());
        if(!SecurityUtils.getLoginUser().getUser().getUserType().equals(UserConstants.USER_TYPE_MANAGER)){
            updateWrapper.eq(CnWorkOrderDetail::getUserType, UserConstants.USER_TYPE_MANAGER);
        } else {
            updateWrapper.ne(CnWorkOrderDetail::getUserType, UserConstants.USER_TYPE_MANAGER);
        }
        updateWrapper.eq(CnWorkOrderDetail::getReadStatus, false);
        updateWrapper.set(CnWorkOrderDetail::getReadStatus, true);
        update(updateWrapper);

        List<CnWorkOrderDetailVO> list = baseMapper.queryList(queryWrapper);
        Collections.reverse(list);
        return list;

    }

    /**
     * 查询工单详细
     *
     * @param id 工单详细主键
     * @return 工单详细
     */
    @Override
    public CnWorkOrderDetail selectCnWorkOrderDetailById(String id) {
        return getById(id);
    }

    /**
     * 新增工单详细
     *
     * @param cnWorkOrderDetail 工单详细
     * @return 结果
     */
    @Override
    public boolean insertCnWorkOrderDetail(CnWorkOrderDetail cnWorkOrderDetail) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        CnWorkOrder workOrder = cnWorkOrderService.getById(cnWorkOrderDetail.getOrderNum());
        if (workOrder == null) {
            throw new ServiceException("工单不存在");
        }
        if (workOrder.getStatus().equals(WorkOrderStatusEnum.CLOSED)) {
            throw new ServiceException("工单已关闭, 无法继续回复");
        }
        cnWorkOrderDetail.setCreateBy(SecurityUtils.getUserId().toString());
        cnWorkOrderDetail.setUserType(loginUser.getUser().getUserType());
        cnWorkOrderDetail.setUserId(SecurityUtils.getUserId());
        return save(cnWorkOrderDetail);
    }

    /**
     * 修改工单详细
     *
     * @param cnWorkOrderDetail 工单详细
     * @return 结果
     */
    @Override
    public boolean updateCnWorkOrderDetail(CnWorkOrderDetail cnWorkOrderDetail) {
        cnWorkOrderDetail.setUpdateBy(SecurityUtils.getUserId().toString());
        cnWorkOrderDetail.setUpdateTime(DateUtils.getNowDate());
        return updateById(cnWorkOrderDetail);
    }

    /**
     * 批量删除工单详细
     *
     * @param ids 需要删除的工单详细主键
     * @return 结果
     */
    @Override
    public boolean deleteCnWorkOrderDetailByIds(List<String> ids) {
        return removeBatchByIds(ids);
    }

    /**
     * 删除工单详细信息
     *
     * @param id 工单详细主键
     * @return 结果
     */
    @Transactional
    @Override
    public boolean deleteCnWorkOrderDetailById(String id) {
      return removeById(id);
    }

    /**
     * 工单已读
     * @param ids 工单id集合
     * @return
     */
    @Override
    public boolean read(List<String> ids) {
        LambdaUpdateWrapper<CnWorkOrderDetail> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(CnWorkOrderDetail::getOrderNum, ids);
        updateWrapper.set(CnWorkOrderDetail::getReadStatus, true);
        return update(updateWrapper);
    }

    @Override
    public long getUnreadNum() {

        long count = 0L;
        List<CnWorkOrder> list = cnWorkOrderService.list(new LambdaQueryWrapper<CnWorkOrder>()
                .eq(CnWorkOrder::getStatus, WorkOrderStatusEnum.IN_PROGRESS.name())
                .eq(CnWorkOrder::getCreateBy, SecurityUtils.getUserId()));
        if (list.size() <= 0) {
            return count;
        }
        List<String> orderNumList = list.stream().map(CnWorkOrder::getOrderNum).collect(Collectors.toList());
        count = this.count(new LambdaQueryWrapper<CnWorkOrderDetail>()
                .eq(CnWorkOrderDetail::getReadStatus, "0")
                .in(CnWorkOrderDetail::getOrderNum, orderNumList)
                .ne(CnWorkOrderDetail::getUserId, SecurityUtils.getUserId()));
        return count;
    }

}
